// stores/materialBatches.js
import { defineStore } from 'pinia'
import { listBatch, updateBatch  } from "@/api/material-service/batch.js";

export const useMaterialBatchStore = defineStore('materialBatches', {
    state: () => ({
        batchList: [],
        materialsMap: new Map(), // 按materialId分组存储批次
        loading: false
    }),
    actions: {
        async fetchBatches() {
            this.loading = true
            try {
                const res = await listBatch({ pageSize: 9999 }) // 获取全部批次
                this.batchList = res.rows
                this.buildMaterialsMap()
            } finally {
                this.loading = false
            }
        },
        buildMaterialsMap() {
            this.materialsMap = this.batchList.reduce((map, batch) => {
                if (!map.has(batch.materialId)) {
                    map.set(batch.materialId, [])
                }
                map.get(batch.materialId).push(batch)
                return map
            }, new Map())
        },
        getBatchesByMaterial(materialId) {
            return this.materialsMap.get(materialId) || []
        },
        // 新增方法：根据batchId获取批次
        getBatchById(batchId) {
            return this.batchList.find(batch => batch.batchId === batchId)
        },
        // 新增方法：更新批次数量
        updateBatchQuantity(batchId, newQuantity) {
            const batch = this.getBatchById(batchId)
            if (batch) {
                batch.currentQuantity = newQuantity
                this.buildMaterialsMap() // 更新后重建映射
            }
        }
    }
})
export default useMaterialBatchStore